Protocol (swift)
interfaceのようなもの
型が持つべき メソッドやプロパティを定義する
code:swift
protocol Animal {
func speak()
}
gpt-5.icon
interfaceと違う部分(Swift特有)
Swiftの protocol は interfaceより機能が多いです。
① デフォルト実装を持てる
code:swift
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Hello")
}
}
準拠する型
code:swift
struct Person: Greetable { }
実装を書かなくても
code:swift
Person().greet()
実行可能。
interfaceより mixinに近い能力があります。
② struct / enum でも採用できる
code:swift
struct Dog: Animal
多くの言語のinterfaceは class向け設計ですが
Swiftは 値型中心の設計です。
protocolは ジェネリックな型制約を持てます
code:swift
protocol Container {
associatedtype Item
func add(_ item: Item)
}
これは普通のinterfaceより 抽象度が高い設計です。
④ SwiftはProtocol中心の設計思想
Swiftは
という設計思想があります。
クラス継承より
code:_
protocol + struct
の組み合わせを推奨しています。
5. 複数protocolの採用
Swiftでは 複数のprotocolを同時に採用できます。
code:swift
protocol Flyable {
func fly()
}
protocol Swimmable {
func swim()
}
struct Duck: Flyable, Swimmable {
func fly() { }
func swim() { }
}